<template>
  <div id="home">
    <el-row>
      <el-col :span="24">
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item>首页</el-breadcrumb-item>
          <el-breadcrumb-item>用户与权限</el-breadcrumb-item>
          <el-breadcrumb-item>角色管理</el-breadcrumb-item>
        </el-breadcrumb>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24" align="right">
        <el-button
          @click="handleAddRole"
          size="small"
          type="success"
          icon="el-icon-circle-plus-outline"
        >添加角色</el-button>
      </el-col>
    </el-row>
    <br>
    <el-row>
      <el-col :span="24">
        <el-table
          ref="tableRole"
          :data="tableRoleData"
          border
          stripe
          fit
          highlight-current-row
          v-loading="tableRoleLoading"
          max-height="1200"
        >
          <el-table-column type="index" label="序号" :index="indexMethod" width="80"></el-table-column>
          <el-table-column prop="name" label="角色名称" width="120"></el-table-column>
          <el-table-column prop="roleDesc" label="描述" width="360" :show-overflow-tooltip="true"></el-table-column>
          <el-table-column prop="created" label="创建日期" :formatter="dateFormat" width="180" sortable></el-table-column>
          <el-table-column prop="updated" label="修改日期" :formatter="dateFormat" width="180" sortable></el-table-column>
          <el-table-column label="操作" width="180">
            <template slot-scope="scope">
              <el-button
                @click="handleEditRole(scope.$index, scope.row)"
                type="text"
                size="small"
              >编辑</el-button>
              <el-button
                @click="handleSetRight(scope.$index, scope.row)"
                type="text"
                size="small"
              >指定权限</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page"
          :page-sizes="[1, 10, 20, 50, 100]"
          :page-size="20"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        ></el-pagination>
      </el-col>
    </el-row>

    <el-dialog
      :title="dialogRoleTitle"
      :visible.sync="dialogRoleVisible"
      width="600px"
      @closed="dialogRoleClosed"
    >
      <el-form ref="formRole" :model="modelRole" status-icon :rules="rulesUser">
        <el-form-item label="角色名称" :label-width="formRoleLabelWidth" prop="name">
          <el-input v-model="modelRole.name" autocomplete="off" maxlength="50"></el-input>
        </el-form-item>
        <el-form-item label="描述" :label-width="formRoleLabelWidth" prop="roleDesc">
          <el-input
            v-model="modelRole.roleDesc"
            autocomplete="off"
            maxlength="100"
            type="textarea"
            :rows="2"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogRoleVisible = false">取 消</el-button>
        <el-button type="primary" :loading="isButtonLoadingRole" @click="onSubmitRole">确 定</el-button>
      </div>
    </el-dialog>

    <el-checkbox-group v-model="checksSetRight">
      <el-dialog
        :title="dialogSetRightTitle"
        :visible.sync="dialogSetRightVisible"
        width="950px"
        @closed="dialogSetRightClosed"
      >
        <el-tree
          :data="dataSetRight"
          default-expand-all
          node-key="id"
          ref="treeSetRight"
          highlight-current
          :props="defaultProps"
          :expand-on-click-node="false"
        >
          <span class="custom-tree-node" slot-scope="{ node, data }">
            <span>{{ node.label }}</span>
            &nbsp;&nbsp;&nbsp;&nbsp;
            <span>
              <template v-for="rightKind in dataRightKindList">
                <el-checkbox
                  :label="getRightId(data.id, rightKind.kind)"
                  :key="getRightId(data.id, rightKind.kind)"
                  v-if="checkRightVisible(data.id, rightKind.kind)"
                >{{rightKind.name}}</el-checkbox>
              </template>
            </span>
          </span>
        </el-tree>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogSetRightVisible = false">取 消</el-button>
          <el-button type="primary" :loading="isButtonLoadingSetRight" @click="onSubmitSetRight">确 定</el-button>
        </div>
      </el-dialog>
    </el-checkbox-group>
  </div>
</template>

<script>
import { getAPI } from '../assets/js/resources.js'
import { formatDate } from '../assets/js/nix.utils.js'
var Qs = require('qs')

export default {
  name: 'Home',
  data() {
    var checkName = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('角色名称不能为空'))
      } else {
        callback()
      }
    }
    var checkRoleDesc = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('描述不能为空'))
      } else {
        callback()
      }
    }
    return {
      page: 1,
      rows: 20,
      total: 100,
      tableRoleData: [],
      tableRoleLoading: false,
      dialogRoleVisible: false,
      dialogRoleTitle: '添加角色',
      modelRole: {
        id: null,
        name: '',
        roleDesc: ''
      },
      rulesUser: {
        name: [{ validator: checkName, trigger: 'blur' }],
        roleDesc: [{ validator: checkRoleDesc, trigger: 'blur' }]
      },
      formRoleLabelWidth: '70px',
      isButtonLoadingRole: false,
      roleIdSetRight: null,
      dialogSetRightTitle: '指定权限',
      dialogSetRightVisible: false,
      isButtonLoadingSetRight: false,
      dataSetRight: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      checksSetRight: [202, 303],
      dataRightList: [],
      dataRightKindList: []
    }
  },
  methods: {
    /* Table */
    loadtableRoleData() {
      this.tableRoleLoading = true
      var that = this
      this.$axios
        .get(getAPI('API_GET_ROLE_LIST'), {
          params: { page: this.page, rows: this.rows }
        })
        .then(function(response) {
          if (response.data.status === 200) {
            that.tableRoleData = response.data.data.list
            that.total = response.data.data.total
            that.tableRoleLoading = false
          } else {
            that.$message.error(response.data.msg)
          }
        })
        .catch(function(error) {
          console.log(error)
        })
    },
    handleSizeChange(val) {
      // console.log('每页' + val + '条');
      this.rows = val
      this.loadtableRoleData()
    },
    handleCurrentChange(val) {
      // console.log('当前页:' + val);
      this.page = val
      this.loadtableRoleData()
    },
    handleAddRole() {
      this.dialogRoleTitle = '添加角色'
      this.dialogRoleVisible = true
    },
    handleEditRole(index, row) {
      // console.log(index, row);
      // this.$message(row.id + '');
      this.dialogRoleTitle = '修改角色'
      this.dialogRoleVisible = true
      this.modelRole.id = row.id
      this.modelRole.name = row.name
      this.modelRole.roleDesc = row.roleDesc
    },
    indexMethod(index) {
      return index + 1
    },
    dateFormat(row, column, cellValue, index) {
      var date = new Date(cellValue)
      return formatDate(date, 'yyyy-MM-dd hh:mm:ss')
    },
    /* Edit */
    onSubmitRole() {
      this.isButtonLoadingRole = true
      this.$refs.formRole.validate(valid => {
        if (valid) {
          var that = this
          this.$axios({
            method: 'post',
            url: getAPI('API_POST_ROLE_SAVE'),
            // 序列化为&格式
            data: Qs.stringify(that.modelRole)
          })
            .then(function(response) {
              if (response.data.status === 200) {
                that.$message({
                  message: '保存成功',
                  type: 'success'
                })
                that.isButtonLoadingRole = false
                that.dialogRoleVisible = false
                that.loadtableRoleData()
              } else {
                that.$message.error(response.data.msg)
                that.isButtonLoadingRole = false
              }
            })
            .catch(function(error) {
              console.log(error)
            })
        }
      })
    },
    resetForm() {
      this.modelRole = {
        id: null,
        username: '',
        phone: '',
        email: '',
        status: 1
      }
      this.$refs.formRole.resetFields()
    },
    dialogRoleClosed() {
      this.resetForm()
    },
    /* Right */
    dialogSetRightClosed() {
      this.checksSetRight = []
    },
    handleSetRight(index, row) {
      this.dialogSetRightTitle = '为角色【' + row.name + '】指定权限'
      this.roleIdSetRight = row.id
      this.dialogSetRightVisible = true
      var that = this
      this.$axios
        .get(getAPI('API_GET_ROLE_RIGHT') + row.id)
        .then(function(response) {
          if (response.data.status === 200) {
            that.checksSetRight = response.data.data
            that.dialogSetRightVisible = true
          } else {
            that.$message.error(response.data.msg)
          }
        })
        .catch(function(error) {
          console.log(error)
        })
    },
    loadDataSetRight() {
      if (JSON.stringify(this.dataSetRight) === '[]') {
        var that = this
        this.$axios
          .get(getAPI('API_GET_MENU_TREE'))
          .then(function(response) {
            if (response.data.status === 200) {
              that.dataSetRight = response.data.data
            } else {
              that.$message.error(response.data.msg)
            }
          })
          .catch(function(error) {
            console.log(error)
          })
      }
    },
    loadDataRightList() {
      if (JSON.stringify(this.dataRightList) === '[]') {
        var that = this
        this.$axios
          .get(getAPI('API_GET_RIGHT_LIST'))
          .then(function(response) {
            if (response.data.status === 200) {
              that.dataRightList = response.data.data
              // 提取RightKindList
              that.dataRightList.forEach(item => {
                var existed = false
                for (var i = 0; i < that.dataRightKindList.length; i++) {
                  if (item.kind === that.dataRightKindList[i].kind) {
                    existed = true
                    break
                  }
                }
                if (!existed) {
                  that.dataRightKindList.push({
                    kind: item.kind,
                    name: item.name
                  })
                }
              })
            } else {
              that.$message.error(response.data.msg)
            }
          })
          .catch(function(error) {
            console.log(error)
          })
      }
    },
    checkRightVisible(menuId, rightKind) {
      var flag = false
      for (var i = 0; i < this.dataRightList.length; i++) {
        if (
          this.dataRightList[i].menuId === menuId &&
          this.dataRightList[i].kind === rightKind
        ) {
          flag = true
          break
        }
      }
      return flag
    },
    getRightId(menuId, rightKind) {
      for (var i = 0; i < this.dataRightList.length; i++) {
        if (
          this.dataRightList[i].menuId === menuId &&
          this.dataRightList[i].kind === rightKind
        ) {
          var rightId = this.dataRightList[i].id
          return rightId
        }
      }
    },
    onSubmitSetRight() {
      this.isButtonLoadingSetRight = true
      var that = this
      this.$axios({
        method: 'post',
        url: getAPI('API_POST_ROLE_SET_RIGHT'),
        // 序列化为&格式
        data: Qs.stringify({
          roleId: this.roleIdSetRight,
          rightIds: this.checksSetRight.join(',')
        })
      })
        .then(function(response) {
          if (response.data.status === 200) {
            that.isButtonLoadingSetRight = false
            that.dialogSetRightVisible = false
          } else {
            that.$message.error(response.data.msg)
          }
        })
        .catch(function(error) {
          console.log(error)
        })
    }
  },
  created() {
    this.loadtableRoleData()
    this.loadDataSetRight()
    this.loadDataRightList()
  }
}
</script>

<style scoped>
</style>
